import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, data) => {
    state.userInfo = data
  }

}

const actions = {
  // 登录
  async login({ commit }, userInfo) {
    const res = await login(userInfo)
    commit('SET_TOKEN', res.token)
    setToken(res.token)
  },

  // 获取用户信息
  async getInfo({ commit, state }) {
    const res = await getInfo()
    commit('SET_USERINFO', res.userInfo)
    // 返回用户信息
    return res
  },

  // 退出登录
  logout({ commit, state }) {
    removeToken() // must remove token first
    // 重置路由
    resetRouter()
    commit('RESET_STATE')
    // 重置侧边栏信息 A模块如何触发B模块的mutation 第三个参数{root: true}
    commit('permission/setRoutes', [], { root: true })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove token first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

